<template>
  <div>
    <p>{{ $store.state.age }}--boy：{{$store.state.boy.boyName}},{{$store.state.boy.boyAge}}</p>
    <p>{{ $store.getters.nextAge }}</p>
    <p>{{ $store.getters.nextAge }}</p>
    <p>{{ $store.getters.nextAge }}</p>
    <button @click="myAge">按时长大</button>
    <br />
    <p>用户名：{{ $store.state.name }}</p>
    <input
      type="text"
      placeholder="尊姓大名"
      v-model="username"
      @keyup.enter="changeName"
    />
    <p>余额：{{ $store.state.money }}</p>
    <button @click="recharge(5)">充值5元</button>
    <button @click="recharge(10)">充值10元</button>
    <br />
    <input type="text" v-model.number="num" />
    <button @click="recharge(num)">自定义充值</button>
    <br />
    <button @click="changeAge">年龄改为20</button>
    <h1>{{ hasWude }}</h1>
    <h1>{{ myName }}</h1>
    <h1>{{ age }}</h1>
    ---
    <p>{{ nextAge }}</p>
    <h1>{{ money }}</h1>
    <button @click="beOld">点击执行beOld</button>
    <button @click="login">login</button>
    <button @click="action1">action1</button>
    <hr>
    <button @click="getUname">获取用户名-{{$store.state.uName}}</button>
    <button @click="getUnameAAA">action版本的获取用户名</button>
  </div>
</template>

<script>
import { ADD } from "../store/mutation-type";
// 引入辅助函数，需要谁引入谁----map映射.将vuex中的数据和方法映射到组件中，就像是组件自己的属性和方法
import { mapState, mapGetters, mapMutations } from "vuex";

export default {
  data() {
    return {
      username: "",
      num: 0,
      name: "AAA",
    };
  },
  computed: {
    // xxx() {
    //   return yyyy
    // },
    ...mapState({
      myName: (state) => state.name, // 为了改名字，采用花括号
      age: (state) => state.age,
      money: (state) => state.money,
      hasWude: (state) => state.hasWude,
    }),
    ...mapGetters([
      // 不该名字时，用方括号
      "nextAge",
    ]),
  },
  methods: {
    ...mapMutations([
      // 映射进来之后，就当作自己的函数来用
      "beOld",
      "changeName",
    ]),
    myAge() {
      this.$store.commit("beOld");
    },
    changeName() {
      // 调用vuex的store中的mutation方法，修改数据
      this.$store.commit("changeName", this.username);
    },
    recharge(num) {
      console.log(num);
      this.$store.commit(ADD, num);
    },
    changeAge() {
      // 对象风格的提交方式，commit一个对象
      this.$store.commit({
        type: "changeAge", // 事件类型
        age: 20,
      });
    },
    login() {
      this.$http.post("/login", { phone: 1111, pwd: 123456 }).then((res) => {
        console.log(res); // 此时已经时同步代码了
        this.$store.commit("changeName", res.data.username);
      });
    },
    // action的演示
    action1() {
      this.$store.dispatch('getData')
    },
    // 友好的方式--啰嗦一点但是简单
    getUname() {
      this.$http('http://localhost:3000/useing/master')
      .then(res => {
        console.log(res[0].uName);
        this.$store.commit("getUname", res[0].uName);
      })
    },
    // action版本的获取用户名
    getUnameAAA() {
      this.$store.dispatch('setUnameAction')
    }
  },
};
</script>

<style>
</style>